<?php
/**
 * 基础函数库
*/

/**
 * F                       实例化FTP库
 * realIp                  获取真实IP地址
 * getCrlf                 获得用户操作系统的换行符
 * getStrLen               获取字符串长度
 * makeDir                 检测目录是否存在，并创建目录
 * addslashesDeep          为数据数组添加字符转义
 * addslashesDeepObj       为对象添加字符转义
 * stripslashesDeep        去除转义
 * checkFileType           检验文件类型
 * ipToAddr                IP转地址
 * moveUploadFile          转移上传文件至新目录
 * sendMail                发送邮件
 * vpost                   模拟用户请求数据
 * microsecond             获取当前微秒时间
 * shutdownFun             脚本执行完时回调的函数
 */

if (!defined('EGGMS'))
{
    die('非法进入');
}

/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function realIp()
{
    static $realIp = NULL;

    if ($realIp !== NULL)
    {
        return $realIp;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);
                if ($ip != 'unknown')
                {
                    $realIp = $ip;
                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realIp = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realIp = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realIp = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realIp = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realIp = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realIp = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realIp, $onlineip);
    $realIp = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
    return $realIp;
}

/**
 * 获得用户操作系统的换行符
 *
 * @access  public
 * @return  string
 */
function getCrlf()
{
/* LF (Line Feed, 0x0A, \N) 和 CR(Carriage Return, 0x0D, \R) */
    if (stristr($_SERVER['HTTP_USER_AGENT'], 'Win'))
    {
        $theCrlf = '\r\n';
    }
    elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac'))
    {
        $theCrlf = '\r'; // for old MAC OS
    }
    else
    {
        $theCrlf = '\n';
    }

    return $theCrlf;
}

/**
 * 计算字符串的长度（中文汉字按照两个字符计算）
 *
 * @param   string      $str        字符串
 *
 * @return  int
 */
function getStrLen($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));
    if ($length)
    {
        return strlen($str) - $length + intval($length / 3) * 2;
    }
    else
    {
        return strlen($str);
    }
}

/**
 * 检查目标文件夹是否存在，如果不存在则自动创建该目录
 *
 * @access      public
 * @param       string      folder     目录路径。不能使用相对于网站根目录的URL
 *
 * @return      bool
 */
function makeDir($folder)
{
    $reval = false;

    if (!file_exists($folder))
    {
        /* 如果目录不存在则尝试创建该目录 */
        @umask(0);

        /* 将目录路径拆分成数组 */
        preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);

        /* 如果第一个字符为/则当作物理路径处理 */
        $base = ($atmp[0][0] == '/') ? '/' : '';

        /* 遍历包含路径信息的数组 */
        foreach ($atmp[1] AS $val)
        {
            if ('' != $val)
            {
                $base .= $val;

                if ('..' == $val || '.' == $val)
                {
                    /* 如果目录为.或者..则直接补/继续下一个循环 */
                    $base .= '/';

                    continue;
                }
            }
            else
            {
                continue;
            }

            $base .= '/';

            if (!file_exists($base))
            {
                /* 尝试创建目录，如果创建失败则继续循环 */
                if (@mkdir(rtrim($base, '/')))
                {
                    @chmod($base);
                    $reval = true;
                }
            }
        }
    }
    else
    {
        /* 路径已经存在。返回该路径是不是一个目录 */
        $reval = is_dir($folder);
    }
    clearstatcache();
    return $reval;
}

/**
 * 递归方式的对变量中的特殊字符进行转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function addslashesDeep($value)
{
    if (empty($value))
    {
        return $value;
    }
    else
    {
        return is_array($value) ? array_map('addslashesDeep', $value) : addslashes($value);
    }
}

/**
 * 将对象成员变量或者数组的特殊字符进行转义
 *
 * @access   public
 * @param    mix        $obj      对象或者数组
 * @author   Xuan Yan
 *
 * @return   mix                  对象或者数组
 */
function addslashesDeepObj($obj)
{
    if (is_object($obj) == true)
    {
        foreach ($obj AS $key => $val)
        {
            $obj->$key = addslashesDeep($val);
        }
    }
    else
    {
        $obj = addslashesDeep($obj);
    }

    return $obj;
}

/**
 * 递归方式的对变量中的特殊字符去除转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function stripslashesDeep($value)
{
    if (empty($value))
    {
        return $value;
    }
    else
    {
        return is_array($value) ? array_map('stripslashesDeep', $value) : stripslashes($value);
    }
}

/**
 * 检查文件类型
 *
 * @access      public
 * @param       string      fileName            文件名
 * @param       string      realName            真实文件名
 * @param       string      limitExtTypes     允许的文件类型
 * @return      string
 */
function checkFileType($fileName, $realName = '', $limitExtTypes = '')
{
    if ($realName)
    {
        $extName = strtolower(substr($realName, strrpos($realName, '.') + 1));
    }
    else
    {
        $extName = strtolower(substr($fileName, strrpos($fileName, '.') + 1));
    }

    if ($limitExtTypes && stristr($limitExtTypes, '|' . $extName . '|') === false)
    {
        return '';
    }

    $str = $format = '';

    $file = @fopen($fileName, 'rb');
    if ($file)
    {
        $str = @fread($file, 0x400); // 读取前 1024 个字节
        @fclose($file);
    }
    else
    {
        if (stristr($fileName, ROOT) === false)
        {
            if ($extName == 'jpg' || $extName == 'jpeg' || $extName == 'gif' || $extName == 'png' || $extName == 'doc' ||
                $extName == 'xls' || $extName == 'txt'  || $extName == 'zip' || $extName == 'rar' || $extName == 'ppt' ||
                $extName == 'pdf' || $extName == 'rm'   || $extName == 'mid' || $extName == 'wav' || $extName == 'bmp' ||
                $extName == 'swf' || $extName == 'chm'  || $extName == 'sql' || $extName == 'cert'|| $extName == 'pptx' || 
                $extName == 'xlsx' || $extName == 'docx')
            {
                $format = $extName;
            }
        }
        else
        {
            return '';
        }
    }

    if ($format == '' && strlen($str) >= 2 )
    {
        if (substr($str, 0, 4) == 'MThd' && $extName != 'txt')
        {
            $format = 'mid';
        }
        elseif (substr($str, 0, 4) == 'RIFF' && $extName == 'wav')
        {
            $format = 'wav';
        }
        elseif (substr($str ,0, 3) == "\xFF\xD8\xFF")
        {
            $format = 'jpg';
        }
        elseif (substr($str ,0, 4) == 'GIF8' && $extName != 'txt')
        {
            $format = 'gif';
        }
        elseif (substr($str ,0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")
        {
            $format = 'png';
        }
        elseif (substr($str ,0, 2) == 'BM' && $extName != 'txt')
        {
            $format = 'bmp';
        }
        elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS') && $extName != 'txt')
        {
            $format = 'swf';
        }
        elseif (substr($str ,0, 4) == "\xD0\xCF\x11\xE0")
        {   // D0CF11E == DOCFILE == Microsoft Office Document
            if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extName == 'doc')
            {
                $format = 'doc';
            }
            elseif (substr($str,0x200,2) == "\x09\x08" || $extName == 'xls')
            {
                $format = 'xls';
            } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extName == 'ppt')
            {
                $format = 'ppt';
            }
        } elseif (substr($str ,0, 4) == "PK\x03\x04")
        {
            if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extName == 'docx')
            {
                $format = 'docx';
            }
            elseif (substr($str,0x200,2) == "\x09\x08" || $extName == 'xlsx')
            {
                $format = 'xlsx';
            } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extName == 'pptx')
            {
                $format = 'pptx';
            }else
            {
                $format = 'zip';
            }
        } elseif (substr($str ,0, 4) == 'Rar!' && $extName != 'txt')
        {
            $format = 'rar';
        } elseif (substr($str ,0, 4) == "\x25PDF")
        {
            $format = 'pdf';
        } elseif (substr($str ,0, 3) == "\x30\x82\x0A")
        {
            $format = 'cert';
        } elseif (substr($str ,0, 4) == 'ITSF' && $extName != 'txt')
        {
            $format = 'chm';
        } elseif (substr($str ,0, 4) == "\x2ERMF")
        {
            $format = 'rm';
        } elseif ($extName == 'sql')
        {
            $format = 'sql';
        } elseif ($extName == 'txt')
        {
            $format = 'txt';
        }
    }

    if ($limitExtTypes && stristr($limitExtTypes, '|' . $format . '|') === false)
    {
        $format = '';
    }

    return $format;
}

/**
 * 将上传文件转移到指定位置
 *
 * @param string $file_name
 * @param string $target_name
 * @return blog
 */
function moveUploadFile($file_name, $target_name = '')
{
    if (function_exists("move_uploaded_file"))
    {
        if (move_uploaded_file($file_name, $target_name))
        {
            @chmod($target_name,0755);
            return true;
        }
        else if (copy($file_name, $target_name))
        {
            @chmod($target_name,0755);
            return true;
        }
    }
    elseif (copy($file_name, $target_name))
    {
        @chmod($target_name,0755);
        return true;
    }
    return false;
}

/**
 * 邮件发送
 *
 * @param: $name[string]        接收人姓名
 * @param: $email[string]       接收人邮件地址
 * @param: $subject[string]     邮件标题
 * @param: $content[string]     邮件内容
 * @param: $type[int]           0 普通邮件， 1 HTML邮件
 * @param: $notification[bool]  true 要求回执， false 不用回执
 *
 * @return boolean
 */
function sendMail($name, $email, $subject, $content, $type = 1, $notification=false)
{
    /* 如果邮件编码不是CHARSET，创建字符集转换对象，转换编码 */
    if ($GLOBALS['_CFG']['mailCharset'] != $GLOBALS['_CFG']['charset'])
    {
        $name      = iconv($GLOBALS['_CFG']['charset'], $GLOBALS['_CFG']['mailCharset'], $name);
        $subject   = iconv($GLOBALS['_CFG']['charset'], $GLOBALS['_CFG']['mailCharset'], $subject);
        $content   = iconv($GLOBALS['_CFG']['charset'], $GLOBALS['_CFG']['mailCharset'], $content);
        $shopName  = iconv($GLOBALS['_CFG']['charset'], $GLOBALS['_CFG']['mailCharset'], $GLOBALS['_CFG']['shopName']);
    }else{
        $shopName = $GLOBALS['_CFG']['shopName'];
    }
    $charset   = $GLOBALS['_CFG']['mailCharset'];
    /**
     * 使用mail函数发送邮件
     */
    if ($GLOBALS['_CFG']['mailService'] == 0 && function_exists('mail'))
    {
        /* 邮件的头部信息 */
        $content_type = ($type == 0) ? 'Content-Type: text/plain; charset=' . $charset : 'Content-Type: text/html; charset=' . $charset;
        $headers = array();
        $headers[] = 'From: "' . '=?' . $charset . '?B?' . base64_encode($shopName) . '?='.'" <' . $GLOBALS['_CFG']['smtpMail'] . '>';
        //$headers[] = 'From: "' . '=?' . $charset . '?B?' . $GLOBALS['_CFG']['smtpMail'];
        $headers[] = $content_type . '; format=flowed';
        if ($notification)
        {
            $headers[] = 'Disposition-Notification-To: ' . '=?' . $charset . '?B?' . base64_encode($shopName) . '?='.'" <' . $GLOBALS['_CFG']['smtpMail'] . '>';
        }

        $res = @mail($email, '=?' . $charset . '?B?' . base64_encode($subject) . '?=', $content, implode("\r\n", $headers));

        if (!$res)
        {
            $GLOBALS['err'] ->add('发送失败');

            return false;
        }
        else
        {
            return true;
        }
    }
    /**
     * 使用smtp服务发送邮件
     */
    else
    {
        /* 邮件的头部信息 */
        $content_type = ($type == 0) ?
            'Content-Type: text/plain; charset=' . $charset : 'Content-Type: text/html; charset=' . $charset;
        $content   =  base64_encode($content);

        $headers = array();
        $headers[] = 'Date: ' . gmdate('D, j M Y H:i:s') . ' +0000';
        $headers[] = 'To: "' . '=?' . $charset . '?B?' . base64_encode($name) . '?=' . '" <' . $email. '>';
        $headers[] = 'From: "' . '=?' . $charset . '?B?' . base64_encode($shopName) . '?='.'" <' . $GLOBALS['_CFG']['smtpMail'] . '>';
        //$headers[] = 'From: "' . '=?' . $charset . '?B?' . $GLOBALS['_CFG']['smtpMail'];
        $headers[] = 'Subject: ' . '=?' . $charset . '?B?' . base64_encode($subject) . '?=';
        $headers[] = $content_type . '; format=flowed';
        $headers[] = 'Content-Transfer-Encoding: base64';
        $headers[] = 'Content-Disposition: inline';
        if ($notification)
        {
            $headers[] = 'Disposition-Notification-To: ' . '=?' . $charset . '?B?' . base64_encode($shopName) . '?='.'" <' . $GLOBALS['_CFG']['smtpMail'] . '>';
        }

        /* 获得邮件服务器的参数设置 */
        $params['host'] = $GLOBALS['_CFG']['smtpHost'];
        $params['port'] = $GLOBALS['_CFG']['smtpPort'];
        $params['user'] = $GLOBALS['_CFG']['smtpUser'];
        $params['pass'] = $GLOBALS['_CFG']['smtpPass'];
        if (empty($params['host']) || empty($params['port']))
        {
            // 如果没有设置主机和端口直接返回 false
            $GLOBALS['err'] ->add('服务器配置出错');

            return false;
        }
        else
        {
            // 发送邮件
            if (!function_exists('fsockopen'))
            {
                //如果fsockopen被禁用，直接返回
                $GLOBALS['err']->add('fsockopen被禁用');

                return false;
            }

            include_once(FW . 'clib/classStmp.php');
            static $smtp;

            $send_params['recipients'] = $email;
            $send_params['headers']    = $headers;
            $send_params['from']       = $GLOBALS['_CFG']['smtpMail'];
            $send_params['body']       = $content;
            if (!isset($smtp))
            {
                $smtp = new classSmtp($params);
            }
            if ($smtp->connect() && $smtp->send($send_params))
            {
                return true;
            }
            else
            {
                $err_msg = $smtp->error_msg();
                if (empty($err_msg))
                {
                    $GLOBALS['err']->add('未知错误');
                }
                else
                {
                    if (strpos($err_msg, 'Failed to connect to server') !== false)
                    {
                        $GLOBALS['err']->add(sprintf('无法连接到邮件服务器 %s', $params['host'] . ':' . $params['port']));
                    }
                    else if (strpos($err_msg, 'AUTH command failed') !== false)
                    {
                        $GLOBALS['err']->add('邮件服务器验证帐号或密码不正确');
                    }
                    elseif (strpos($err_msg, 'bad sequence of commands') !== false)
                    {
                        $GLOBALS['err']->add('服务器拒绝发送该邮件');
                    }
                    else
                    {
                        $GLOBALS['err']->add($err_msg);
                    }
                }
                return false;
            }
        }
    }
}

/**
 * 模仿用户请求
 *
 * @param: $url[string]        请求地址
 * @param: $data[json]       请求数据
 *
 * @return $tmpInfo 数据
 */
function vpost($url,$data=""){ // 模拟提交数据函数

    if(is_array($data)){
        require_once(FW . 'clib/classJson.php');
        $json = new classJson();
        $data = 'v_data='.urlencode($json->encode($data));
    }
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); // 模拟用户使用的浏览器
    // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    // curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包x
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
       echo 'Errno'.curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $tmpInfo; // 返回数据
}

/**
 * IP地址转换成地区,返回数组
 * @param   string      $ip        ip字符串
 * @return  array
 */
function I2A($ipAddr)
{
    if (!empty($GLOBALS['IPTOADDR'])) {
        $addr = $GLOBALS['IPTOADDR']->ipToAddr($ipAddr);
    } else {
        require_once(FW . 'clib/classIpToAddr.php');
        $GLOBALS['IPTOADDR'] = new classIpToAddr();
        $addr = $GLOBALS['IPTOADDR']->ipToAddr($ipAddr);
    }
    return $addr['country'];
}

/**
  * 实例化FTP类
  */
function F($k = 0) {
    if (!empty($GLOBALS['FTP'][$k])) {
        // 如果已经实例化，则直接返回
        return $GLOBALS['FTP'][$k];
    } elseif (!empty($GLOBALS['_CFG']['FTP'][$k])) {
        // 否则如果存在配置并未实例化，则实例化并返回
        include_once(FW . 'clib/classFtp.php');
        $GLOBALS['FTP'][$k] = new classFtp($GLOBALS['_CFG']['FTP'][$k]);
        if (!empty($GLOBALS['FTP'][$k]->conn_id)) {
            return $GLOBALS['FTP'][$k];
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
 * 实例化数据库
 */
function D() {
    if (!empty($GLOBALS['DB'])) {
        // 如果已经实例化，则直接返回
        return $GLOBALS['DB'];
    } else {
        /* 加载实例化数据库类 */
        if (!empty($GLOBALS['_CFG']['db']['host']) && !empty($GLOBALS['_CFG']['db']['user']) && !empty($GLOBALS['_CFG']['db']['pass']) && !empty($GLOBALS['_CFG']['db']['name']) && !empty($GLOBALS['_CFG']['db']['charset'])) {
            // 加载mysqli类文件
            require(FW . 'clib/classMysql.php');
            if (!empty($GLOBALS['_CFG']['db']['type']) && $GLOBALS['_CFG']['db']['type'] == 'mysqli') {
                $GLOBALS['DB'] = new classMysqli($GLOBALS['_CFG']['db'], false, $GLOBALS['_CFG']['db']['read']);
            }
            // 设置数据表缓存时间
            $GLOBALS['DB']->setMaxCacheTime($GLOBALS['_CFG']['db']['cacheTime']);
            return $GLOBALS['DB'];
        } else {
            die('No DBConfig In Config File');
        }
    }
}

/**
  * 实例化缓存
  */
function M($k = 0) {
    if (!empty($GLOBALS['MEMCACHED'][$k])) {
        // 如果已经实例化，则直接返回
        return $GLOBALS['MEMCACHED'][$k];
    } else {
        /* 实例化memcached类 */
        if (!empty($GLOBALS['_CFG']['memcachedServer'][$k])) {
            $GLOBALS['MEMCACHED'][$k] = new memcached();
            // 检测是否有密码验证
            if (!empty($GLOBALS['_CFG']['memcachedServer'][$k]['user']) && !empty($GLOBALS['_CFG']['memcachedServer'][$k]['pass']))
            {
                // 使用binary二进制协议
                $GLOBALS['MEMCACHED'][$k]->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
                // 添加服务池
                $GLOBALS['MEMCACHED'][$k]->addServer($GLOBALS['_CFG']['memcachedServer'][$k]['host'], $GLOBALS['_CFG']['memcachedServer'][$k]['port']);
                // 进行密码验证
                $GLOBALS['MEMCACHED'][$k]->setSaslAuthData($GLOBALS['_CFG']['memcachedServer'][$k]['user'],$GLOBALS['_CFG']['memcachedServer'][$k]['pass']);
            } else {
                // 添加服务池
                $GLOBALS['MEMCACHED'][$k]->addServer($GLOBALS['_CFG']['memcachedServer'][$k]['host'],$GLOBALS['_CFG']['memcachedServer'][$k]['port']) ;
            }
        }
    }
}

/**
 * 实例化库存
 */
function S() {
    if (!empty($GLOBALS['STOCK'])) {
        // 如果已经实例化，则直接返回
        return $GLOBALS['STOCK'];
    } else {
        // 否则如果存在配置并未实例化，则实例化并返回
        include_once(FW . 'clib/classStock.php');
        $GLOBALS['STOCK'] = new classStock();
        return $GLOBALS['STOCK'];
    }
}

/**
 * 实例化队列
 */
function Q() {
    if (!empty($GLOBALS['QUEUE'])) {
        // 如果已经实例化，则直接返回
        return $GLOBALS['QUEUE'];
    } else {
        // 否则如果存在配置并未实例化，则实例化并返回
        include_once(FW . 'clib/classQueue.php');
        $GLOBALS['QUEUE'] = new classQueue();
        return $GLOBALS['QUEUE'];
    }
}

/**
 * 实例化队列
 */
function C() {
    if (!empty($GLOBALS['COUNTER'])) {
        // 如果已经实例化，则直接返回
        return $GLOBALS['COUNTER'];
    } else {
        // 否则如果存在配置并未实例化，则实例化并返回
        include_once(FW . 'clib/classCounter.php');
        $GLOBALS['COUNTER'] = new classCounter();
        return $GLOBALS['COUNTER'];
    }
}

/**
 * 实例化邮件发送类
 */
function E() {
    if (!empty($GLOBALS['EMAIL'])) {
        // 如果已经实例化，则直接返回
        return $GLOBALS['EMAIL'];
    } else {
        // 否则如果存在配置并未实例化，则实例化并返回
        include_once(FW . 'clib/classSmtp.php');
        $GLOBALS['EMAIL'] = new classSmtp($GLOBALS['_CFG']['EMAIL']);
        return $GLOBALS['EMAIL'];
    }
}

/**
 * 实例化JSON数据处理类
 */
function J() {
    if (!empty($GLOBALS['JSON'])) {
        // 如果已经实例化，则直接返回
        return $GLOBALS['JSON'];
    } else {
        // 否则如果存在配置并未实例化，则实例化并返回
        include_once(FW . 'clib/classJson.php');
        $GLOBALS['JSON'] = new classJson();
        return $GLOBALS['JSON'];
    }
}

/**
 * 实例化UPLOAD数据处理类
 */
function U() {
    if (!empty($GLOBALS['UPLOAD'])) {
        // 如果已经实例化，则直接返回
        return $GLOBALS['UPLOAD'];
    } else {
        // 否则如果存在配置并未实例化，则实例化并返回
        include_once(FW . 'clib/classUpload.php');
        $GLOBALS['UPLOAD'] = new classUpload();
        return $GLOBALS['UPLOAD'];
    }
}

/**
 * 实例化图像处理类
 */
function I() {
    if (!empty($GLOBALS['IMAGES'])) {
        // 如果已经实例化，则直接返回
        return $GLOBALS['IMAGES'];
    } else {
        // 否则如果存在配置并未实例化，则实例化并返回
        include_once(FW . 'clib/classImage.php');
        $GLOBALS['IMAGES'] = new classImage();
        return $GLOBALS['IMAGES'];
    }
}

/**
 * 获取数据表的名字
 */
function T($name, $key = 'db') {
    if (!empty($name)) {
        return D($key)->table($name);
    } else {
        return false;
    }
}

/**
 * 获取微秒级的时间戳
 *
 * @return $时间戳
 */
function microsecond(){
    list($usec, $sec) = explode(" ",microtime());
    return ((float)$usec + (float)$sec);
}

/**
 * 默认程序关闭回调函数
 *
 * @return 打印脚本运行时间
 */
function shutdownFun(){
    if($GLOBALS['_CFG']['debug'] == 2){
        $timeStart = TIMESTART;
        $timeEnd = microsecond();
        $doTime = $timeEnd - $timeStart;
        echo '<pre>运行时长：'.$doTime.'</pre>';
        print_r(error_get_last());
    }else{
        return false;
    }
}

?>